﻿namespace Core.Providers.DataAccess.Implementation
{
	using FluentNHibernate.AutoMap;
	using FluentNHibernate.Cfg;
	using FluentNHibernate.Cfg.Db;
	using NHibernate;

	internal class NHibernateDataAccessProvider : IDataAccessProvider
	{
		public ISessionFactory CreateSessionFactory()
		{
			return Fluently.Configure()
				.Database(CreateConfiguration())
				.Mappings(m => m.AutoMappings.Add(CreateAutoPersistenceModel()))
				.BuildSessionFactory();
		}
		
		private static IPersistenceConfigurer CreateConfiguration()
		{
			return MsSqlConfiguration.MsSql2005
				.ConnectionString(e => e.Server(".\\sqlexpress").Database("IMeetYou").TrustedConnection())
				.DefaultSchema("Main")
				.ShowSql();
		}

		private static AutoPersistenceModel CreateAutoPersistenceModel()
		{
			return AutoPersistenceModel.MapEntitiesFromAssemblyOf<NHibernateDataAccessProvider>()
				.Where(type => type.Namespace.EndsWith("Domain")
						&& type.Name.EndsWith("Service") == false)
				.WithConvention(convention =>
				{
					convention.GetPrimaryKeyNameFromType = type => type.Name + "Id";
					// TODO Following is my singular to plural coversion...
					convention.GetTableName = type => type.Name + "s";
					convention.GetForeignKeyNameOfParent = type => type.Name + "Id";
					convention.GetForeignKeyName = type => type.Name + "Id";
					convention.DefaultStringLength = 255;
				});
		}
	}
}
